import 'dart:math';

import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:smart_devices/model/spare_part.dart';
import 'package:smart_devices/params/spare_part.dart';

class DeviceSparePartLogic extends GetxController {
  RxInt total = RxInt(0);

  RxString search = RxString('');

  late RefreshController refreshController;

  RxList<SparePartModel> pageList = RxList([]);

  @override
  void onInit() {
    super.onInit();
    var r = Random();
    for (var i = 0; i < 10; i++) {
      pageList.add(SparePartModel(
          imgUrl:
              'https://img0.baidu.com/it/u=2949872195,3712487931&fm=253&fmt=auto&app=138&f=JPEG?w=746&h=500',
          name: '备件00${r.nextInt(100)}',
          code: 'SB179001$i',
          model: '30*50*20',
          unit: SparePartUnitEnum.all,
          type: SparePartTypeEnum.main,
          change: r.nextInt(10) + 2,
          inventory: r.nextInt(300) + 50,
          count: r.nextInt(100) + 100));
    }
    refreshController = RefreshController(initialRefresh: false);
    Map<String, dynamic> args = Get.arguments ?? {'total': 15, 'id': 1};
    total.value = args['total'];
  }

  @override
  void onClose() {
    super.onClose();
    refreshController.dispose();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 15) {
      return refreshController.loadNoData();
    }

    /// 添加
    refreshController.loadComplete();
    var r = Random();
    pageList.add(SparePartModel(
        imgUrl:
            'https://img0.baidu.com/it/u=2949872195,3712487931&fm=253&fmt=auto&app=138&f=JPEG?w=746&h=500',
        name: '电机备件',
        code: 'SB149897${pageList.length + 1}',
        count: r.nextInt(100) + 100,
        unit: SparePartUnitEnum.all,
        type: SparePartTypeEnum.main,
        change: r.nextInt(10) + 5,
        inventory: r.nextInt(240) + 100,
        model: '30*50*20'));
  }
}
